<template>
  <div>
    <!-- B端计划财务审核 -->
    <TopFilter ref="topfrom"  :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="planFinancialAuditSideB"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :isSelectColumn="false"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" @click="addHandle()">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="emmitVisible" :title="'计划审核'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <emitModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="detailVisible" :title="'计划信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <detailModel :rowData="formData" @close="detailcloseHandler" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getList, exportList, exporturl } from '@/api/omSale/salesPlan/planFinancialAuditSideB/index.js';
import emitModel from './emitModel';
import detailModel from './detailModel';
import { exportExcelFile } from '@/utils';
import { region } from '@/api/cms-common/region';
import { getSaleAreaInfo } from '@/api/cms-common/dealerdata/index';
import { dealerCommon } from '@/api/cms-api/origin/commonDealerType';		//渠道类型工具类
import moment from 'moment';
export default {
  name: 'planFinancialAuditSideB',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchParams: { 
        auditType:'Finance' 
      },
      fetchApi: getList,
      formData: {},
      exportLoading: false,
      emmitVisible: false,
      detailVisible: false,
      regionList:[],
      areaList: []
    };
  },
  mixins: [dictionary,region,dealerCommon],
  components: {
    emitModel,
    detailModel
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    //默认查询条件
    this.fetchParams.planYearAndMonth =  this.topFilterList.find((x) => x.fieldName == 'planYearAndMonth').initialValue;
    //查询状态过滤
    this.getQueryStatus();
    //初始化销售战区
    this.getAreaData();
    //初始化省份信息
    this.initProvince();
  },
  methods: {
    createdFrom() {
      return [
         {
          type: 'INPUT',
          label: '计划编号',
          fieldName: 'plan1No',
          placeholder: '请输入'
        },
        {
          type: 'DATE',
          label: '计划年月',
          fieldName: 'planYearAndMonth',
          initialValue: moment().add(1,'months').format('YYYY-MM'),
          dateType: 'month'
        },
        {
          type: 'SELECT',
          label: '计划状态',
          fieldName: 'planStatus',
          placeholder: '请选择',
          itemList: []
        },
        { 
          type: 'SELECT', 
          label: 'B端战区', 
          fieldName: 'areaId', 
          placeholder: '请选择',  
          itemList: [] 
        },
        { 
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          itemList: [],
          change: (value) => {
            this.initCity(value)
          },
        },
        { 
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          itemList:[]
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)} disabled={props.row.planStatus != 21031002}>
                  审核
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                  详情
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '计划编号',
          dataIndex: 'plan1No',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'B端战区',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            return <span>{
              this.getareaName(props.row.areaId)}</span>;
          }
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '状态',
          dataIndex: 'planStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          render: p => {
            return <span>{this.createDictText(p.row.planStatus, '2103')}</span>;
          }
        },
        {
          title: '计划年月',
          dataIndex: 'planYearAndMonth',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '提报数量',
          dataIndex: 'quantity',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '提报人',
          dataIndex: 'reportPersonName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '提报日期',
          dataIndex: 'reportDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        }
      ];
    },
    //初始化销售战区信息
    async getAreaData() {
      const res = await getSaleAreaInfo(15061016);
      if (res.resultCode === 200) {
        this.areaList = res.data;
        res.data.map((x) => {
          this.topFilterList.find((item) => item.fieldName == 'areaId').itemList.push({ text: x.orgName, value: x.id });
        });
      }
    },
      //获取战区名称
    getareaName(value) {
     if (this.areaList.length > 0) {
        for (let i in this.areaList) {
        if (this.areaList[i].id === value) {
          return this.areaList[i].orgName;
        }
      }
     }
    },
    //初始化所在省份
    async initProvince(){
      let pl = this.createRegionList();
      this.topFilterList[4].itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId){
      //清空市
      this.topFilterList[5].initialValue="";
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      this.topFilterList[5].itemList = cl;
    },
   async addHandle() {

      // let json = Object.assign({}, { CODE: 'CODE_0000034' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }

        this.$refs.topfrom.SUBMIT_FORM();

        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let json = this.fetchParams;
            this.exportLoading = true;

            exportList(json)
              .then(response => {
                exportExcelFile(response.data, 'B端计划财务审核');
                this.exportLoading = false;
              })
              .catch(err => {
                console.log(err);
              });
          })
          .catch(() => {
            console.log('456');
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
    },
    //查询状态过滤
    getQueryStatus() {
      let statusList = this.createDictList('2103');
      console.log('所有状态',statusList);
      let index = statusList.findIndex(item =>{
　　　　　if(item.value == 21031001){
　　　　　　　return true
　　　　　}
　　　})
      statusList.splice(index, 1);
      this.topFilterList.find(item => item.fieldName == 'planStatus').itemList = statusList;
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async editHandle(data, type) {
      this.formData = data;
      if (type == 1) {
        this.emmitVisible = true;
      } else if (type == 2) {
        this.detailVisible = true;
      } 
    },
    emitcloseHandler(val) {
      this.emmitVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    addcloseHandler(val) {
      this.addVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    detailcloseHandler() {
      this.detailVisible = false;
    }
  }
};
</script>
